package com.faintlight.dto;

import com.faintlight.model.Capsule;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Data
public class CapsuleDTO {
    private static final Logger logger = LoggerFactory.getLogger(CapsuleDTO.class);

    private Long id;
    private String title;
    private String content;
    private String unlockTime;
    private String status;
    private String countdown;
    private Integer temperature;
    private String createdAt;
    // 新增：接收人信息
    private String recipientName;
    private String imageUrl;

    public static CapsuleDTO fromEntity(Capsule capsule) {
        logger.debug("🔄 转换胶囊实体为 DTO: ID={}, 标题={}", capsule.getId(), capsule.getTitle());
        CapsuleDTO dto = new CapsuleDTO();
        dto.setId(capsule.getId());
        dto.setTitle(capsule.getTitle());
        dto.setContent(capsule.getContent());
        dto.setUnlockTime(capsule.getUnlockTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        dto.setStatus(capsule.getDisplayStatus());
        dto.setTemperature(capsule.getTemperature());
        dto.setCreatedAt(capsule.getCreatedAt() != null ? capsule.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) : "");
        dto.setRecipientName(capsule.getRecipientName());
        dto.setImageUrl(capsule.getImageUrl());
        LocalDateTime now = LocalDateTime.now();
        if (capsule.getUnlockTime().isAfter(now)) {
            Duration duration = Duration.between(now, capsule.getUnlockTime());
            long days = duration.toDays();
            long hours = duration.toHours() % 24;
            dto.setCountdown(String.format("距离解锁还有%d天%d小时", days, hours));
            logger.debug("⏳ 距离解锁: {}天{}小时", days, hours);
        } else {
            dto.setCountdown("已解锁");
            logger.debug("✅ 胶囊已解锁");
        }

        return dto;
    }
}